package com.example.sw.myapptes2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.sw.myapptes2.Bean.User;

import org.litepal.LitePal;

import java.util.List;

public class LoginActivity extends AppCompatActivity {
    private EditText usnEdit,pswEdit;
    private Button loginbtn;
    List<User> userList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        setListener();
        initUser();


    }

    private void initUser() {
        userList= LitePal.findAll(User.class);
        Log.e("123",userList.size()+"");
        if (userList.size()==0){
            new User(0,"zhangsan","123").save();
            new User(0,"lisi","456").save();
            new User(0,"wangwu","789").save();
        }
    }

    private void setListener() {
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String usn=usnEdit.getText().toString();
                String psw=pswEdit.getText().toString();
                User u=confirmLogin(usn,psw);
                if (u==null){
                    showToast("账号或密码输入有误");
                }else {
                    showToast("登录成功");

                    SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putInt("uid",u.getId());
                    editor.putString("usn",u.getUsername());
                    editor.putString("psw",u.getPassword());
                    editor.apply();


                    Intent intent= new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                }

            }
        });

    }


    private void showToast(String s) {
        Toast.makeText(LoginActivity.this,s,Toast.LENGTH_SHORT).show();
    }

    private User confirmLogin(String usn, String psw) {
        //获取User的所有信息
        userList = LitePal.findAll(User.class);
        for (User u : userList) {
            if (u.getUsername().equals(usn) && u.getPassword().equals(psw)) {
                return u;
            }
        }

        return null;

    }

    private void initView() {
        usnEdit = findViewById(R.id.usnEdit);
        pswEdit = findViewById(R.id.pswEdit);
        loginbtn = findViewById(R.id.loginbtn);




    }


}

